package com.zhb.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhb.entity.Account;
import com.zhb.mapper.AccountMapper;
import com.zhb.service.IAccountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.SQLException;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhb
 * @since 2021-09-09
 */
@Service
@AllArgsConstructor
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements IAccountService {

    private final AccountMapper accountMapper;

    @Override
    public void reduce(String accountCode, BigDecimal amount) {
        Account account = new Account();
        account.setAccountCode(accountCode);
        Wrapper<Account> queryWrapper = new QueryWrapper<>(account);
        account = accountMapper.selectOne(queryWrapper);
        if (null == account) {
            throw new RuntimeException("can't reduce amount,account is null");
        }
        BigDecimal subAmount = account.getAmount().subtract(amount);
        if (subAmount.compareTo(BigDecimal.ZERO) < 0) {
            throw new RuntimeException("can't reduce amount,account'amount is less than reduce amount");
        }
        account.setAmount(subAmount);
        accountMapper.updateById(account);
    }
}
